package NO15;

/**
 * 输入一个链表，输出该链表中倒数第k个结点。
 * @author swg
 *
 */
public class FindKthToTail {
	public class ListNode {
	    int val;
	    ListNode next = null;

	    ListNode(int val) {
	        this.val = val;
	    }
	}
	
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k <= 0){
            return null;
        } 
        
         //定义一个pre节点指向head
         ListNode pre = head;
         //定义一个last节点指向head
         ListNode last = head;
         
     	for(int i=0;i<k-1;i++){
             if(last.next != null){
                 last = last.next;
             }else{
                 return null;
             }
         }
     	while(!(last.next==null)){
     		pre = pre.next;
     		last = last.next;
     	}
     	
     	return pre;
     }
}
